from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from django.http import JsonResponse, HttpResponse
from ihome.libs.captcha.captcha import captcha
from celery_tasks.sms.tasks import ccp_send_sms_code
from users.models import User
from django.contrib.auth import login,authenticate,logout

from ihome.utils.views import LoginRequiredJsonMixin
from ihome.utils.ImageCheck import image_file
from ihome.libs.qiniuyun.qiniu_storage import storage

import json,re


# Create your views here.
# 手机号是否重复
class RegisterView(View):
    def post(self,request):
        #1.提取参数
        data = json.loads(request.body.decode())
        mobile =data.get('mobile')
        phonecode = data.get('phonecode')
        password = data.get('password')
        #2.校验参数
        if not all([mobile,phonecode,password]):
            return JsonResponse({'errno':4103,'errmsg':'缺少必要参数'})

        if not re.match(r'1[3-9]\d{9}', mobile):
            return JsonResponse({'errno': 4103, 'errmsg': '手机号有误'})

        #3.业务数据处理
        #3.1手机号是否重复
        try:
            count = User.objects.filter(mobile=mobile).count()
        except User.DoesNotExist:
            return JsonResponse({'errno':4001,'errmsg':'数据库查询出错'})

        if count != 0:
            return JsonResponse({'errno':4001,'errmsg':'手机号重复注册'})

        #3.2未重复注册，校验密码
        if not re.match(r'^[0-9a-zA-Z_-]{8,20}$', password)  :
            return JsonResponse({'errno':4004,'errmsg':'密码格式有误'})

        #3.3 短信验证码是否正确
        conn = get_redis_connection('verify_code')
        sms_code = conn.get('sms_code_%s'%mobile)

        if not sms_code:
            return JsonResponse({'errno':4004,'errmsg':'短信验证码过期'})

        if phonecode != sms_code.decode():
            return JsonResponse({'errno':4004,'errmsg':'短信验证码错误'})

        #保存用户
        user = User.objects.create_user(
            username = mobile,
            mobile = mobile,
            password = password
        )

        #设置保持状态，session
        login(request, user=user)

        #4.构建响应
        response = JsonResponse({
            'errno':0,'errmsg':'注册成功'
        })

        #设置cookie
        response.set_cookie('mobile', mobile,3600*24*30)
        return response


# 传统用户名密码登录
class LoginView(View):
    def post(self,request):
        # 从请求体中提取参数
        data = json.loads(request.body.decode())
        username = data.get('mobile')
        password = data.get('password')

        # 校验参数
        if not all([username, password]):
            return JsonResponse({"errno": 4103, "errmsg": "缺少参数"})
        if not re.match(r'1[3-9]\d{9}',username):
            return JsonResponse({"errno": 4103, "errmsg": "参数mobile错误"})
        if not re.match(r'^[a-zA-Z0-9_-]{8,20}$', password):
            return JsonResponse({'errno': 4004, 'errmsg': '密码不符合格式要求'})
        # 调用django自带的authenticate参数进行用户名密码验证
        user = authenticate(request, username=username, password=password)
        if not user:
            # 如果验证失败,返回响应
            return JsonResponse({'errno':4101,'errmsg':'用户名或密码错误'})
        # TODO:状态保持
        login(request,user)

        # 判断是否记住用户,若用户勾选记住密码,remembered返回值为True
        response = JsonResponse({'errno':0,'errmsg':'登陆成功'})
        # TODO 设置cookie,记录用户名
        response.set_cookie('username',user.username,max_age=3600*24*14)
        # merge_cart_cookie_to_redis(request=request, response=response)
        return response


    #判断用户是否登陆
    def get(self,request):
        #1.提取参数
        user = request.user
        #2.校验参数
        #3.业务数据处理
        #3.1未登录
        if not user.is_authenticated:
            return JsonResponse({'errno':4101,'errmsg':'未登录'})
        #4.构建响应
        # user = User.objects.get(pk=user)
        data = {'name':user.username,'user_id':user.id}
        return JsonResponse({
            'errno':0,
            'errmsg':'已登录',
            'data': data
            })

    #退出登录
    def delete(self,request):
        logout(request)
        response = JsonResponse({'errno':0,'errmsg':'已登出'})
        response.delete_cookie('username')
        return response


#个人中心
class UserInfoView(View,LoginRequiredJsonMixin):
    def get(self,request):
        #1.提取参数
        user = request.user
        # user = User.objects.get(pk = user.id)
        try:
            avatar_url =user.avatar.url
            print(type(avatar_url))
            print(avatar_url)
        except Exception as e:
            avatar_url = ''
        #2.校验参数
        #3.业务数据处理
        #4.构建响应
        data = {
            'avatar_url':avatar_url,
            'create_time':user.create_time,
            'mobile':user.mobile,
            'name':user.username,
            'user_id':user.id
        }
        return JsonResponse({
            'errno':0,
            'errmsg':'ok',
            'data':data
        })



# 上传头像
class UserAvatarView(View,LoginRequiredJsonMixin):
    def post(self,request):
        #1.提取参数
        user = request.user
        file = request.FILES.get('avatar')

        #2.校验参数
        #判断是否上传了图片
        file_type = image_file(file)
        if not file_type:
            return JsonResponse({'errno':4001,'errmsg':'上传的不是图片'})


        filedata = file.read()
        #3.业务数据处理
        #3.1上传头像
        try:

            image_url = storage(filedata)

            # print(image_url)
        except Exception as e:
            return JsonResponse({'errno':4001,'errmsg':'上传头像失败'})

        #3.2写入头像信息
        try:
            user.avatar = image_url
            user.save()
        except Exception as e:
            return JsonResponse({'errno':4001,'errmsg':'上传头像失败'})

        #4.构建响应

        data ={'avatar_url':user.avatar.url}
        return JsonResponse({'errno':0,'errmsg':'ok','data':data})


# 用户名修改
class UesrnameUpdataView(LoginRequiredJsonMixin, View):
    def put(self, request):
        # 1.提取参数
        user = request.user
        data = json.loads(request.body.decode())
        new_username = data.get('name')

        # 2.校验参数
        if not new_username:
            return JsonResponse({'errno': 4041, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[a-zA-Z0-9_-]{2,20}$', new_username):
            return JsonResponse({'errno': 4041, 'errmsg': '用户名格式有误'})

        # 3.业务数据处理：修改用户名
        try:
            user.username = new_username
            user.save()
        except Exception as e:
            return JsonResponse({'errno': 4041, 'errmsg': '用户名修改错误'})

        # 清理状态保持信息
        logout(request)

        response = JsonResponse({'errno': '0', 'errmsg': '修改成功'})
        response.delete_cookie('username')
        return response


# 用户实名认证
class UesrAuthentificationView(LoginRequiredJsonMixin, View):
    def post(self, request):
        # 1.提取参数
        user = request.user
        data = json.loads(request.body.decode())
        real_name = data.get('real_name')
        id_card = data.get('id_card')

        # 2.校验参数
        if not all([real_name, id_card]):
            return JsonResponse({'errno': 4041, 'errmsg': '缺少必传参数'})

        if not re.match(r'^\w{5,20}$', real_name):
            return JsonResponse({'errno': 4041, 'errmsg': '真实名字格式错误'})

        if not re.match(
                r'(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)',
                id_card):
            return JsonResponse({'errno': 4041, 'errmsg': '身份证格式错误'})

        # 3.业务数据处理,添加真实名字和身份证号
        try:
            user.real_name = real_name
            user.id_card = id_card
            user.save()
        except Exception as e:
            return JsonResponse({'errno': 0, 'errmsg': '实名认证失败'})

        return JsonResponse({'errno': '0', 'errmsg': '认证信息保存成功'})


    def get(self, request):
        user = request.user
        data = {
            'real_name': user.real_name,
            'id_card': user.id_card
        }
        return JsonResponse({'errno': '0', 'errmsg': '认证成功', 'data': data})